function addImage() {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.addEventListener('change', function () {
        var file = this.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function (e) {
                var img = new Image();
                img.src = e.target.result;
                img.onload = function () {
                    // 图片压缩逻辑（保持不变）
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    var maxWidth = 800;
                    var maxHeight = 600;
                    var width = img.width;
                    var height = img.height;

                    if (width > maxWidth) {
                        height = height * (maxWidth / width);
                        width = maxWidth;
                    }
                    if (height > maxHeight) {
                        width = width * (maxHeight / height);
                        height = maxHeight;
                    }

                    canvas.width = width;
                    canvas.height = height;
                    ctx.drawImage(img, 0, 0, width, height);

                    canvas.toBlob(function (blob) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var base64Image = e.target.result;

                            // 1. 本地先显示自己的图片（带“(我)”标识）
                            setMessageInnerHTML(`${currentNick}(我): <img src="${base64Image}" alt="图片" style="max-width: 200px;">`);

                            // 2. 构建消息对象（使用标准JSON，避免手动拼接）
                            const message = {
                                type: "image",
                                msg: base64Image,
                                group: currentGroup,
                                sendUser: currentNick // 添加发送者信息
                            };

                            // 3. 添加包头并发送
                            const messageWithHeader = addHeader(JSON.stringify(message));
                            if (webSocket.readyState === WebSocket.OPEN) {
                                webSocket.send(messageWithHeader);
                            } else {
                                console.error("WebSocket连接未就绪");
                            }
                        };
                        reader.readAsDataURL(blob);
                    }, file.type, 0.2); // 图片质量
                };
            };
            reader.readAsDataURL(file);
        }
    });
    input.click();
}

// 辅助函数：格式化文件大小
function formatFileSize(bytes) {
    if (bytes < 1024) return bytes + 'B';
    else if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + 'KB';
    else return (bytes / 1024 / 1024).toFixed(1) + 'MB';
}

// 修改 uploadFile 函数，使用二进制分片传输
// 修改文件上传逻辑（分片+二进制传输）
function uploadFile() {
    const input = document.createElement('input');
    input.type = 'file';
    input.addEventListener('change', function () {
        const file = this.files[0];
        if (!file) return;

        // 1. 发送元数据
        const metadata = {
            type: "file_meta",
            fileName: file.name,
            fileSize: file.size,
            group: currentGroup,
            sendUser: currentNick
        };
        setMessageInnerHTML(`${currentNick}(我): 开始上传文件 ${file.name} [上传中...]`);

        const metadataWithHeader = addHeader(JSON.stringify(metadata));
        webSocket.send(metadataWithHeader);

        // 2. 分片传输
        const CHUNK_SIZE = 1 * 1024 * 1024;
        let offset = 0;
        const reader = new FileReader();

        const readNextChunk = () => {
            const slice = file.slice(offset, Math.min(offset + CHUNK_SIZE, file.size));
            reader.readAsArrayBuffer(slice);
        };

        reader.onload = (e) => {
            const chunkData = e.target.result;
            webSocket.send(chunkData);
            offset += chunkData.byteLength;

            // 显示上传进度
            const progress = Math.min((offset / file.size) * 100, 100);
            setMessageInnerHTML(`${currentNick}(我): 文件 ${file.name} 上传进度: ${progress.toFixed(2)}%`);

            // 所有分片发送完成后更新状态
            if (offset >= file.size) {
                setMessageInnerHTML(`${currentNick}(我): 文件 ${file.name} 上传完成`);
            } else {
                readNextChunk();
            }
        };

        readNextChunk();
    });
    input.click();
}